import {
  reactive,
  ref,
  shallowRef,
  shallowReactive,
  computed,
  onMounted,
  onUnmounted,
  getCurrentInstance,
  toRaw,
} from "vue";
import { globalConfig } from "@gd-accbuild-core/config";
import { isSuccessReqBackend, getBackendDataItems, treeTools } from "@gd-accbuild-core/config/utils";

const transTreeData = (data, isLazy) => {
  if (isLazy) {
    return data;
  } else {
    const res = treeTools.invertTree({ sourceArr: data });
    return res.result;
  }
};
/**
 * 左树点击传递到右表的参数
 * @param {Array} arr [{orgKey:"",targetKey:""}]
 * @param {any} val 值
 * @param {obj} res
 */
export const getAppendReqParams = (arr, val, res = {}) => {
  arr.forEach((el) => {
    res[el.targetKey] = val[el.orgKey];
  });
  return res;
};
/**
 * 按钮的合并策略: 包括按钮的文字、点击事件等
 */
const getMergeBtnsConfig = (remoteData, staticData) => {
  remoteData.size = staticData.size;
  staticData.buttons.forEach((btn) => {
    const matchedRemoteBtnIdx = remoteData.buttons.findIndex((el) => el.key === btn.key);
    if (matchedRemoteBtnIdx !== -1) {
      remoteData.buttons[matchedRemoteBtnIdx] = btn;
    } else {
      remoteData.buttons.push(btn);
    }
  });
  return remoteData;
};
/**
 * data数据的合并策略: 有远程的用远程的;即本地的初始化时起作用后面不会用到
 */
const getMergedData = (remoteData, staticData) => {
  const isArrStructMetaData = Array.isArray(remoteData) || Array.isArray(staticData);
  if (!staticData) {
    staticData = isArrStructMetaData ? [] : {};
  }
  if (isArrStructMetaData) {
    if (remoteData.length === 0) {
      remoteData = staticData;
      return remoteData;
    } else {
      return remoteData;
    }
  } else {
    if (Object.keys(remoteData).length === 0) {
      remoteData = staticData;
      return remoteData;
    } else {
      return remoteData;
    }
  }
};
/**
 * 两个对象 或 两个数组 属性合并,取并集
 * 合并策略:优先使用本地的
 */
const getMergedMeta = (remoteData, staticData) => {
  const isArrStructMetaData = Array.isArray(remoteData) || Array.isArray(staticData);
  if (!staticData) {
    staticData = isArrStructMetaData ? [] : {};
  }
  if (isArrStructMetaData) {
    const overrideMetaListLen = staticData.length;
    if (remoteData.length > overrideMetaListLen) {
      staticData.forEach((metaItem) => {
        const overrideIdx = remoteData.findIndex((el) => el.key === metaItem.key);
        remoteData[overrideIdx] = metaItem;
      });
      return remoteData;
    } else {
      return staticData;
    }
  } else {
    const ret = {};
    Object.keys(remoteData).forEach((key) => {
      ret[key] = staticData[key];
    });
    return ret;
  }
};
/**
 * 合并远程配置与本地配置
 */
const mergedAllBtnsEmitFormItemMetaConfig = ({
  props,
  staticAllBtnsEmitFormItemMetaConfigAlias,
  remoteAllBtnsEmitFormItemMetaConfigProxy,
}) => {
  Object.keys(props[staticAllBtnsEmitFormItemMetaConfigAlias]).forEach((btnKey) => {
    if (Array.isArray(remoteAllBtnsEmitFormItemMetaConfigProxy[btnKey])) {
      props[staticAllBtnsEmitFormItemMetaConfigAlias][btnKey].forEach((formItemMeta) => {
        const overrideIdx = remoteAllBtnsEmitFormItemMetaConfigProxy[btnKey].findIndex(
          (el) => el.key === formItemMeta.key
        );
        if (overrideIdx !== -1) {
          //TODO:FIXME: 这里标记位raw其他合并策略是否需要此操作待确定
          remoteAllBtnsEmitFormItemMetaConfigProxy[btnKey][overrideIdx] = formItemMeta;
        }
      });
    } else {
      remoteAllBtnsEmitFormItemMetaConfigProxy[btnKey] = props[staticAllBtnsEmitFormItemMetaConfigAlias][btnKey];
    }
  });
  return remoteAllBtnsEmitFormItemMetaConfigProxy;
};
/**
 * 元数据合并: 本地 + 远程
 */
export default ({ props }) => {
  //汇总的数据
  const crudServiceVmTemplateConfig = reactive({
    tree: {},
    table: {},
  });
  const isUseStaticResource = computed(() => {
    const staticResource = props.staticResource;
    return staticResource && Object.keys(staticResource).length > 0;
  });
  /** 容器所有属性合并策略 */
  const setterCrudServiceVmTemplateConfig = (type = "table", templateState) => {
    if (type === "table") {
      const isStaticResourceTable =
        props.staticResource &&
        props.staticResource.uiOptions &&
        props.staticResource.uiOptions.pageUiTemplateConfigs[0].templateProps.hasOwnProperty("tableCommonAttr");
      if (templateState && templateState.curPageUiTemplateConfig.templateProps?.tableCommonAttr) {
        crudServiceVmTemplateConfig.table = templateState.curPageUiTemplateConfig.templateProps.tableCommonAttr ?? {};
      }
      if (isStaticResourceTable) {
        crudServiceVmTemplateConfig.table =
          props.staticResource.uiOptions.pageUiTemplateConfigs[0].templateProps["tableCommonAttr"];
      }
    } else if (type === "tree") {
      if (templateState) {
        crudServiceVmTemplateConfig.tree = templateState.curPageUiTemplateConfig.filter_tableCommonAttr;
      }
      const isStaticResourceTree =
        props.staticResource &&
        props.staticResource.uiOptions &&
        props.staticResource.uiOptions.pageUiTemplateConfigs[0].templateProps.hasOwnProperty("filter_tableCommonAttr");
      if (isStaticResourceTree) {
        crudServiceVmTemplateConfig.tree =
          props.staticResource.uiOptions.pageUiTemplateConfigs[0].templateProps["filter_tableCommonAttr"];
      }
    }
  };
  //////合并容器元数据

  //////合并按钮触发的表单元数据;设计时不存在,运行时存在
  //表相关
  const remoteAllBtnsEmitFormItemMetaConfig = shallowReactive({});
  const allBtnsEmitFormItemMetaConfig = computed(() => {
    return mergedAllBtnsEmitFormItemMetaConfig({
      props,
      staticAllBtnsEmitFormItemMetaConfigAlias: "staticAllBtnsEmitFormItemMetaConfig",
      remoteAllBtnsEmitFormItemMetaConfigProxy: remoteAllBtnsEmitFormItemMetaConfig,
    });
  });
  //树相关
  const remote_filter_allBtnsEmitFormItemMetaConfig = shallowReactive({});
  const filter_allBtnsEmitFormItemMetaConfig = computed(() => {
    console.log("监听到树弹窗变化", props, remote_filter_allBtnsEmitFormItemMetaConfig);
    return mergedAllBtnsEmitFormItemMetaConfig({
      props,
      staticAllBtnsEmitFormItemMetaConfigAlias: "staticFilterAllBtnsEmitFormItemMetaConfig",
      remoteAllBtnsEmitFormItemMetaConfigProxy: remote_filter_allBtnsEmitFormItemMetaConfig,
    });
  });
  ///////合并树的元数据
  const remote_filter_tableCommonAttr = shallowRef({});
  const filter_tableCommonAttr = computed(() => {
    return getMergedMeta(remote_filter_tableCommonAttr.value, crudServiceVmTemplateConfig.tree);
  });
  const remote_filter_toolBarConfig = shallowReactive({
    size: "default",
    buttons: [],
  });
  const filter_toolBarConfig = computed(() => {
    if (crudServiceVmTemplateConfig.tree.hasOwnProperty("toolBarConfig")) {
      return getMergeBtnsConfig(remote_filter_toolBarConfig, crudServiceVmTemplateConfig.tree.toolBarConfig);
    } else {
      return remote_filter_toolBarConfig;
    }
  });
  const remote_filter_operationBtnsConfig = shallowReactive({
    size: "default",
    buttons: [
      {
        key: "buildInAddBtn",
      },
    ],
  });
  const filter_operationBtnsConfig = computed(() => {
    console.log(crudServiceVmTemplateConfig.tree, "树的操作按钮列表====");
    if (crudServiceVmTemplateConfig.tree.hasOwnProperty("operationBtnsConfig")) {
      return getMergeBtnsConfig(
        remote_filter_operationBtnsConfig,
        crudServiceVmTemplateConfig.tree.operationBtnsConfig
      );
    } else {
      return remote_filter_operationBtnsConfig;
    }
  });
  const filter_setterAllTableBtnsConfig = (templateState) => {
    const matchedVmCode = templateState.curPageUiTemplateConfig.vmCode;
    const matchedModuleCode = templateState.curPageUiTemplateConfig.moduleCode;
    remote_filter_toolBarConfig.buttons = [
      {
        key: "buildInAddBtn",
        vmCode: matchedVmCode,
        moduleCode: matchedModuleCode,
      },
    ];
    remote_filter_operationBtnsConfig.buttons = [
      {
        key: "buildInEditBtn",
        vmCode: matchedVmCode,
        moduleCode: matchedModuleCode,
      },
      {
        key: "buildInAddChildIntoCurBtn",
        vmCode: matchedVmCode,
        moduleCode: matchedModuleCode,
      },
      {
        key: "buildInRowDeleteBtn",
        vmCode: matchedVmCode,
        moduleCode: matchedModuleCode,
      },
    ];
  };
  const remote_filter_tableBodyData = shallowRef([]);
  const filter_tableBodyData = computed({
    get: () => {
      return getMergedData(remote_filter_tableBodyData.value, props.staticFilterTableBodyData);
    },
    set: (val) => {
      remote_filter_tableBodyData.value = val;
    },
  });
  const remote_filter_dialogFormItemDynmicConfigList = shallowRef([]);
  const filter_dialogFormItemDynmicConfigList = computed(() => {
    return getMergedMeta(
      remote_filter_dialogFormItemDynmicConfigList.value,
      props.staticFilterDialogFormItemDynmicConfigList
    );
  });
  const filter_setterRemoteTableConfig = (templateState, _emits) => {
    const errorFirst = !templateState.curPageUiTemplateMetaList.hasOwnProperty("tableColMetaList");
    if (errorFirst) {
      return;
    }
    remote_filter_tableCommonAttr.value = templateState.curPageUiTemplateConfig;
    remote_filter_allBtnsEmitFormItemMetaConfig["buildInAddOrEditBtn"] =
      templateState.curPageUiTemplateMetaList.dialogFormItemMetaList;

    remote_filter_dialogFormItemDynmicConfigList.value =
      templateState.curPageUiTemplateMetaList.dialogFormItemDynmicConfigList;
    /////
    const isLazy = templateState.curPageUiTemplateConfig?.lazy ?? false;
    remote_filter_tableBodyData.value = transTreeData(templateState.curPageUiTemplateData.data ?? [], isLazy);
    _emits && _emits("biz-tree-simple:filter-data:init", { data: remote_filter_tableBodyData.value });
    //////
  };
  //const appendFieldsIntoSearchForm = reactive({});
  /** 左树右XX组件时,左侧树默认第一个节点自动点击,所以需要传递到右表组件  */
  const filter_getFirstItemAppendReqParamsIntoSearchForm = (appendReqParams = {}) => {
    const appendFieldsIntoSearchForm = remote_filter_tableCommonAttr.value?.["appendFieldsIntoSearchForm"] ?? [];
    if (remote_filter_tableBodyData.value.length > 0 && appendFieldsIntoSearchForm.length > 0) {
      const treeFirstItem = remote_filter_tableBodyData.value[0];
      appendFieldsIntoSearchForm.forEach((el) => {
        appendReqParams[el.targetKey] = treeFirstItem[el.orgKey];
      });
    }
    return appendReqParams;
  };
  ///////合并主表的元数据
  const remoteTableCommonAttr = shallowRef({
    /*  treeTableConfig: {
                  rowField: "field-key",
                  treeNodeKeys: ["field-key"],
                },
                editConfig: { trigger: "click", mode: "cell" },
                */
    size: "default",
    paginationConfig: {
      isPaged: false,
      pageObj: {
        pageNum: 0,
        pageSize: 0,
        totalCount: 0,
      },
    },
  });
  const tableCommonAttr = computed(() => {
    return getMergedMeta(remoteTableCommonAttr.value, crudServiceVmTemplateConfig.table);
  });
  const remoteTableColMetaList = shallowRef([]);
  const tableColMetaList = computed(() => {
    return getMergedMeta(remoteTableColMetaList.value, props.staticTableColMetaList);
  });
  const remoteTableColumnDynmicConfigList = shallowRef([]);
  const tableColumnDynmicConfigList = computed(() => {
    return getMergedMeta(remoteTableColumnDynmicConfigList.value, props.staticTableColumnDynmicConfigList);
  });
  const remoteDialogFormItemDynmicConfigList = shallowRef([]);
  const dialogFormItemDynmicConfigList = computed(() => {
    return getMergedMeta(remoteDialogFormItemDynmicConfigList.value, props.staticDialogFormItemDynmicConfigList);
  });
  const remoteTableBodyData = shallowRef([]);
  const tableBodyData = computed({
    get: () => {
      return getMergedData(remoteTableBodyData.value, props.staticTableBodyData);
    },
    set: (val) => {
      remoteTableBodyData.value = val;
    },
  });
  const setterRemoteTableConfig = (templateState) => {
    const errorFirst = !templateState.curPageUiTemplateMetaList.hasOwnProperty("tableColMetaList");
    if (errorFirst) {
      return;
    }
    remoteTableCommonAttr.value = templateState.curPageUiTemplateConfig.templateProps?.tableCommonAttr ?? {};
    if (!remoteTableCommonAttr.value.size) {
      remoteTableCommonAttr.value.size = "default";
    }
    if (!remoteTableCommonAttr.value.paginationConfig) {
      remoteTableCommonAttr.value.paginationConfig = {
        isPaged: false,
        pageObj: {
          pageNum: 0,
          pageSize: 0,
          totalCount: 0,
        },
      };
    }
    ////
    let data = [];
    if (!templateState.curPageUiTemplateData?.isEnterReqData) {
      data = [];
    } else {
      data = templateState.curPageUiTemplateData.data ?? [];
    }
    remoteTableBodyData.value = data;
    remoteTableColMetaList.value = templateState.curPageUiTemplateMetaList.tableColMetaList;
    remoteTableColumnDynmicConfigList.value = templateState.curPageUiTemplateMetaList.tableColumnDynmicConfigList;
    //按钮触发的弹窗元数据
    remoteAllBtnsEmitFormItemMetaConfig["buildInAddOrEditBtn"] =
      templateState.curPageUiTemplateMetaList.dialogFormItemMetaList;
    remoteDialogFormItemDynmicConfigList.value = templateState.curPageUiTemplateMetaList.dialogFormItemDynmicConfigList;
  };
  ///////合并主表的搜索表单元数据
  const remoteSearchFormItemMetaList = shallowRef([]);
  const searchFormItemMetaList = computed(() => {
    return getMergedMeta(remoteSearchFormItemMetaList.value, props.staticSearchFormItemMetaList);
  });
  const remoteSearchFormItemDynmicConfigList = shallowRef([]);
  const searchFormItemDynmicConfigList = computed(() => {
    return getMergedMeta(remoteSearchFormItemDynmicConfigList.value, props.staticSearchFormItemDynmicConfigList);
  });
  const remoteSearchFormCommonAttr = shallowRef({
    formLayoutStyle: "Dropdown",
    size: "default",
  });
  const searchFormCommonAttr = computed(() => {
    return getMergedMeta(remoteSearchFormCommonAttr.value, crudServiceVmTemplateConfig.table.searchFormCommonAttr);
  });
  const remoteSearchFormData = shallowRef({});
  const searchFormData = computed({
    get: () => {
      return getMergedData(remoteSearchFormData.value, props.staticSearchFormData);
    },
    set: (val) => {
      remoteSearchFormData.value = val;
    },
  });

  const setterRemoteSearchFormConfig = (templateState) => {
    const errorFirst = !templateState.curPageUiTemplateMetaList.hasOwnProperty("searchFormItemMetaList");
    if (errorFirst) {
      return;
    }
    const curSearchFormItemMetaList = templateState.curPageUiTemplateMetaList.searchFormItemMetaList;
    remoteSearchFormItemMetaList.value = curSearchFormItemMetaList;
    const searchData = {};
    curSearchFormItemMetaList.forEach((el) => {
      searchData[el.key] = undefined;
    });
    remoteSearchFormData.value = searchData;

    remoteSearchFormItemDynmicConfigList.value = templateState.curPageUiTemplateMetaList.searchFormItemDynmicConfigList;
  };
  //////主表的操作按钮、toolbar按钮
  /**
   * 所有表格中的操作按钮本身的配置;按钮文字、颜色,点击事件,beforeClick,containerAttr等
   */
  const remoteOperationBtnsConfig = shallowReactive({
    size: "default",
    buttons: [
      {
        key: "buildInAddChildIntoCurBtn",
      },
      {
        key: "buildInRowDeleteBtn",
      },
      {
        key: "buildInEditBtn",
      },
      {
        key: "buildInDetailBtn",
      },
    ],
  });
  const operationBtnsConfig = computed(() => {
    if (crudServiceVmTemplateConfig.table.hasOwnProperty("operationBtnsConfig")) {
      return getMergeBtnsConfig(remoteOperationBtnsConfig, crudServiceVmTemplateConfig.table.operationBtnsConfig);
    } else {
      return remoteOperationBtnsConfig;
    }
  });
  /**
   * 工具条中的按钮本身的配置;按钮文字、图标、颜色,点击事件,beforeClick,containerAttr等----其中containerAttr中包含了各自的bottomBtnsConfig
   */
  const remoteToolBarConfig = shallowReactive({
    size: "default",
    buttons: [
      {
        key: "buildInAddBtn",
      },
      {
        key: "buildInBatchDeleteBtn",
      },
    ],
  });
  const toolBarConfig = computed(() => {
    if (crudServiceVmTemplateConfig.table.hasOwnProperty("toolBarConfig")) {
      return getMergeBtnsConfig(remoteToolBarConfig, crudServiceVmTemplateConfig.table.toolBarConfig);
    } else {
      return remoteToolBarConfig;
    }
  });
  const setterAllTableBtnsConfig = (templateState) => {
    const errorFirst = !templateState.curPageUiTemplateMetaList.hasOwnProperty("tableColMetaList");
    if (errorFirst) {
      return;
    }
    //console.log(dialogFormItemDynmicConfigList.value, "弹窗动态元数据");
    const matchedVmCode = templateState.curPageUiTemplateConfig.templateProps?.tableCommonAttr?.vmCode;
    const matchedModuleCode = templateState.curPageUiTemplateConfig.templateProps?.tableCommonAttr?.moduleCode;
    const operationBtnsCfg = remoteTableCommonAttr.value?.operationBtnsConfig ?? {
      buttons: [],
    };
    remoteOperationBtnsConfig.buttons = [
      {
        key: "buildInAddChildIntoCurBtn",
        vmCode: matchedVmCode,
        moduleCode: matchedModuleCode,
      },
      {
        key: "buildInRowDeleteBtn",
        vmCode: matchedVmCode,
        moduleCode: matchedModuleCode,
      },
      {
        key: "buildInEditBtn",
        vmCode: matchedVmCode,
        moduleCode: matchedModuleCode,
      },
      {
        key: "buildInDetailBtn",
        vmCode: matchedVmCode,
        moduleCode: matchedModuleCode,
      },
    ];
    operationBtnsCfg.buttons.forEach((el) => {
      const matchedBuildInBtnIdx = remoteOperationBtnsConfig.buttons.findIndex((btn) => btn.key === el.key);
      if (matchedBuildInBtnIdx > -1) {
        remoteOperationBtnsConfig.buttons[matchedBuildInBtnIdx].isShow = el.isShow;
      }
    });
    remoteToolBarConfig.buttons = [
      {
        key: "buildInAddBtn",
        vmCode: matchedVmCode,
        moduleCode: matchedModuleCode,
      },
      {
        key: "buildInBatchDeleteBtn",
        vmCode: matchedVmCode,
        moduleCode: matchedModuleCode,
      },
    ];
  };
  //////////////////////////////
  const fillFieldsIntoAddForm = reactive({});
  const appendFieldsIntoSearchForm = reactive({});
  /**
   * 主表请求的条件拦截
   */
  const isAllowReqData = (params) => {
    const isAllow = new Function("configObj", crudServiceVmTemplateConfig.table?.allowReqDataFunc ?? "return true")(
      params
    );
    return isAllow;
  };
  const tablePageReq = async () => {
    const params = appendFieldsIntoSearchForm;
    if (!isAllowReqData(params)) {
      return;
    }
    //url的参数
    if (tableCommonAttr.value.hasOwnProperty("appendUrlParamsIntoSearchForm")) {
      //const injectAppendUrlParamsIntoSearchForm = {};
      tableCommonAttr.value["appendUrlParamsIntoSearchForm"].forEach((el) => {
        //injectAppendUrlParamsIntoSearchForm[el.targetKey] = getQueryString(el.orgKey);
        searchFormData.value[el.targetKey] = getQueryString(el.orgKey);
      });
    }
    //搜索表单的参数
    const curSearchFormData = searchFormData.value;
    const appendSearchFormData = {};
    Object.keys(curSearchFormData)
      .filter((key) => curSearchFormData[key] !== undefined)
      .forEach((key) => {
        appendSearchFormData[key] = curSearchFormData[key];
      });
    //默认的参数
    const defaultTableReqParams = crudServiceVmTemplateConfig.table?.params ?? {};
    const res = await globalConfig.getList({
      moduleCode: crudServiceVmTemplateConfig.table.moduleCode,
      vmCode: crudServiceVmTemplateConfig.table.vmCode,
      params: {
        ...defaultTableReqParams,
        ...appendSearchFormData,
        ...params,
        isPaged: tableCommonAttr.value?.paginationConfig?.isPaged ?? false,
        pageNum: tableCommonAttr.value?.paginationConfig?.pageObj?.pageNum ?? 0,
        pageSize: tableCommonAttr.value?.paginationConfig?.pageObj?.pageSize ?? 0,
      },
      vmTemplateConfig: crudServiceVmTemplateConfig.table,
    });
    if (isSuccessReqBackend(res)) {
      tableBodyData.value = getBackendDataItems(res);
    }
  };
  //////////////////////////////
  return {
    crudServiceVmTemplateConfig,
    isUseStaticResource,
    setterCrudServiceVmTemplateConfig,
    /** 按钮触发表单的允许时元数据 */
    allBtnsEmitFormItemMetaConfig,
    filter_allBtnsEmitFormItemMetaConfig,
    /** 表按钮配置 */
    operationBtnsConfig,
    toolBarConfig,
    setterAllTableBtnsConfig,
    /** 树按钮配置 */
    filter_toolBarConfig,
    filter_operationBtnsConfig,
    filter_setterAllTableBtnsConfig,
    ////
    filter_tableCommonAttr,
    filter_tableBodyData,
    filter_dialogFormItemDynmicConfigList,
    filter_setterRemoteTableConfig,
    /** 左树右XX组件时,左侧树默认第一个节点自动点击,所以需要传递到右表组件  */
    filter_getFirstItemAppendReqParamsIntoSearchForm,
    ////
    tableCommonAttr,
    tableColMetaList,
    tableColumnDynmicConfigList,
    tableBodyData,
    dialogFormItemDynmicConfigList,
    setterRemoteTableConfig,
    ////
    searchFormItemMetaList,
    searchFormItemDynmicConfigList,
    searchFormCommonAttr,
    searchFormData,
    /** 远程的搜索表单配置的setter */
    setterRemoteSearchFormConfig,
    ////////
    fillFieldsIntoAddForm,
    appendFieldsIntoSearchForm,
    tablePageReq,
  };
};
